package com.kevis.zhunblog.admin.controller.utils;

import cn.hutool.json.JSONException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.upload.IStorageManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@CrossOrigin
@Controller
@RequestMapping("/ueditor")
public class UEditorController {

    @GetMapping("/tt")
    @ResponseBody
    public String showPage() {
        return "index";
    }

    // 读取配置文件中配置的上传文件保存地址
//    @Value("${file.save.location}")
//    private String ueditorUrl;

    /**
     * 接收和获取百度编辑插件的文件，需要注意以下几点
     * 1，需要在 ueditorUrl 目录下创建 ueditor 目录，将 config.json 拷贝到该路径下
     * 2，必须将 ueditorUrl 目录设置为静态资源路径，否则上传的文件可能无法访问
     * 3，注意访问配置文件的方式 ueditor.config.js 请求的路径就是 config.json 放置的同级路径
     */
//    @RequestMapping("upload")
//    public String upload(HttpServletRequest request, String action) {
//        String result = new ActionEnter(request, ueditorUrl).exec();
//        ueditorUrl = ueditorUrl.replaceAll("\\", "/");
//        if (action != null && (action.equals("listfile") || action.equals("listimage"))) {
//            return result.replaceAll(ueditorUrl, "");
//        }
//        return result;
//    }

    @Autowired
    private IStorageManager uploader; // 在spring.xml文件中根据项目实际情况加载具体的实现类

    /*
    官方的方式，可直接保存到插件目录下
     */
    @RequestMapping("upload")
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/html");

        //String rootPath = request.getServletContext().getRealPath("/");
        String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/plugins/editor/UEditor/";
        //解决路径是中文的问题
        rootPath = java.net.URLDecoder.decode(rootPath, "utf-8");

        response.setCharacterEncoding("utf-8");
        String exec = new ActionEnter(uploader, request, rootPath, "config.json").exec();
        PrintWriter writer = response.getWriter();
        writer.write(exec);
        writer.flush();
        writer.close();
    }

    /*
    自己实现，不使用百度编辑器提供的后台方法
     */
    @RequestMapping(value = "/ueconfig")
    public void config(HttpServletRequest request, HttpServletResponse response) throws JSONException {
        response.setContentType("application/json");

        String action = request.getParameter("action");

        switch (action) {
            case "config":
                getUeConfig(response);
                break;
            case "uploadimage":

                break;
        }


    }

    /*
    仿照底层写的，根据配置文件路径返回 config.json
     */
    private void getUeConfig(HttpServletResponse response) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/static/plugins/editor/UEditor/config.json");
            StringBuilder resultStringBuilder = new StringBuilder();
            try (BufferedReader br
                         = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = br.readLine()) != null) {
                    resultStringBuilder.append(line).append("\n");
                }
            }
            String exec = resultStringBuilder.toString();
            //去掉注释
            exec = exec.replaceAll("/\\*[\\s\\S]*?\\*/", "");
            //转为json对象,如果转失败，说明格式不正确
            try {
                JSONObject jsonConfig = JSON.parseObject(exec);
                exec = jsonConfig.toJSONString();
            } catch (Exception e) {
                exec = "";
            }

            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//         @RequestMapping("/upload")
//     public void exec(@RequestParam(value="action",required=false)String action,
//             @RequestParam(value="callback",required=false)String callback,
//             HttpServletRequest req, HttpServletResponse res) {
//                 try {
//                         req.setCharacterEncoding("utf-8");
//                         res.setHeader("Content-Type", "text/html");
//                         String rootPath =req.getSession().getServletContext().getRealPath("/");
//                         res.getWriter().write(new ActionEnter(req, rootPath,"").exec());
//                     } catch (Exception e) {
//                         e.printStackTrace();
//                     }
//             }
}
